#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

'''
mpybuild

Example:

    python3 mpytools/mpybuild.py --src ./src/ --build ./build --mpy-cross "~/micropython/mpy-cross/mpy-cross -O2 -march=xtensawin"

'''

import os
import shutil


def _build(mpycc, src_path, build_path):
    '''递归构建'''
    # build目录是否存在，不存在则创建
    if not os.path.isdir(build_path):
        os.mkdir(build_path)
        print("mkdir {}".format(build_path))

    for file in os.listdir(src_path):
        # print(file)
        # 文件或目录
        target = os.path.join(src_path, file)

        if os.path.isdir(target):
            # print(file)
            _build(mpycc, target, os.path.join(build_path, file))

        elif os.path.isfile(target):
            if (file.endswith(".py")) and (file != "main.py"):
                # 获取文件名，不包含后缀
                file_name, _ = os.path.splitext(os.path.basename(file))

                build_cmd = "{} {} -o {}".format(
                    mpycc, target,
                    os.path.join(build_path, "{}.mpy".format(file_name))
                )
                print(build_cmd)
                os.system(build_cmd)
            else:
                dst_file = os.path.join(build_path, file)
                shutil.copyfile(target, dst_file)
                print("copyfile src: {}  dst: {}".format(target, dst_file))


def main():
    import argparse

    cmd_parser = argparse.ArgumentParser(description="")
    cmd_parser.add_argument(
        "--src", type=str, required=True,
        help="source directory",
    )
    cmd_parser.add_argument(
        "--build", type=str, required=True,
        help="build directory",
    )
    cmd_parser.add_argument(
        "--mpy-cross", type=str, required=True,
        help="mpy-cross path and parameters",
    )

    args = cmd_parser.parse_args()

    # print(args)

    _build(args.mpy_cross, args.src, args.build)


if __name__ == "__main__":
    main()
